package com.pjc.utils;

import java.io.FileInputStream;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigUtil implements Runnable {

	private static Logger log = LoggerFactory.getLogger(ConfigUtil.class);

	private static ConfigUtil config;

	private static final long PERIOD = 1000 * 60 * 30L;

	private Properties properties = new Properties();

	private static ConcurrentHashMap<String, String> sysMsgMap = new ConcurrentHashMap<String, String>();

	private ConfigUtil() {

	}

	public static ConfigUtil getInstance() {
		if (null == config) {
			synchronized (ConfigUtil.class) {
				config = new ConfigUtil();
			}
		}
		return config;
	}

	public void initConfig(Class<?> cla, String fileName) throws Exception {
		String path = SystemUtil.GetConfigPath(cla, fileName);
		log.debug("config.properties配置文件-path:{}", path);
		properties.load(new FileInputStream(path));
	}

	public boolean initConfig(Class<?> mainClass) throws Exception {
		try {
			String path = SystemUtil.GetConfigPath(mainClass, "config.properties");
			log.debug("配置文件-path:{}",path);
			properties.load(new FileInputStream(path));
			return true;
		} catch (Exception e) {
			log.info("config.properties配置文件异常!");
			return false;
		}
	}

	public String getStringProperties(String key) {

		return properties.getProperty(key);
	}

	public int getIntProperties(String key) {
		String val = properties.getProperty(key);
		if (StringUtils.isBlank(val)) {
			return 999;
		}
		return Integer.parseInt(val);
	}

	public String getStringProperties(String key, String defaultVal) {

		String val = properties.getProperty(key);
		if (StringUtils.isBlank(val)) {
			return defaultVal;
		}
		return val;
	}

	public int getIntProperties(String key, int defaultVal) {
		String val = properties.getProperty(key);
		if (StringUtils.isBlank(val)) {
			return defaultVal;
		}
		return Integer.parseInt(val);
	}

	public String getSysMsg(String sysMsgKey, String defaultMsg) {
		String sysMsgStr = (String) sysMsgMap.get(sysMsgKey);
		if (StringUtils.isEmpty(sysMsgStr)) {
			return defaultMsg;
		}
		return sysMsgStr;
	}

	public int getSysMsg(String sysMsgKey, int defaultVal) {
		String sysMsgStr = (String) sysMsgMap.get(sysMsgKey);
		if (StringUtils.isEmpty(sysMsgStr)) {
			return defaultVal;
		}
		return NumberUtils.toInt(sysMsgStr, defaultVal);
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(PERIOD);
			} catch (Exception e) {
				log.error("配置文件线程启动异常!");
			}

		}

	}
}
